using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Soft1ApiDemo.Domain;
using Soft1ApiDemo.Domain.Repository;
using Soft1ApiDemo.Infrastructure.Db;

namespace Soft1ApiDemo.Infrastructure.Repository
{
    public class RepositoryBase<T> : IRepository<T> where T : BaseEntity
    {
        private readonly Soft1ApiDemoDbContext _db;

        private readonly DbSet<T> _table;

        public RepositoryBase(Soft1ApiDemoDbContext db)
        {
            _db = db;
            _table = _db.Set<T>();
        }

        public IQueryable<T> Table
        {
            get
            {
                return _table.AsNoTracking();
            }
        }

        public T GetById(Guid id)
        {
            var entity =
                _db
                    .Set<T>()
                    .AsQueryable()
                    .Where(x => x.Id == id)
                    .FirstOrDefault();
            return entity;
        }

        public T Add(T entity)
        {
            entity.IsActived = true;
            entity.IsDeleted = false;
            entity.CreatedAt = DateTime.Now;
            entity.UpdatedAt = DateTime.Now;
            entity.DisplayOrder = 0;
            _table.Add(entity);
            _db.SaveChanges();
            return entity;
        }

        public void Update(T entity)
        {
            entity.UpdatedAt = DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }

        public void Delete(Guid id)
        {
            var entity = this.GetById(id);
            if (entity != null)
            {
                entity.IsDeleted = true;
                this.Update(entity);
            }
        }

        public async Task<IEnumerable<T>> AddBulk(IEnumerable<T> entities)
        {
            foreach (var item in entities)
            {
                item.IsActived = true;
                item.IsDeleted = false;
                item.CreatedAt = DateTime.Now;
                item.UpdatedAt = DateTime.Now;
            }

            await _table.AddRangeAsync(entities);
            await _db.SaveChangesAsync();
            return entities;
        }

        public async Task<T> GetByIdAsync(Guid id)
        {
            var entity=await _table.FirstOrDefaultAsync(x=>x.Id==id);
            return entity;
        }
    }
}
